package com.n.passwordbook.Utils;

import com.n.passwordbook.PasswordBook.PasswordBook;
import com.n.passwordbook.PasswordBook.PasswordStruct;
import org.apache.commons.lang3.StringUtils;

import java.util.Comparator;
import java.util.Locale;

public class Searcher
{
    private static final int BIGGER = 1;
    private static final int EQUAL = 0;
    private static final int SMALLER = -1;

    public static void search(String txt)
    {
        String[] keyWords = StringUtils.split(txt, ' ');
        PasswordBook.Passwords.parallelStream().forEach(password -> {
            password.setSortingWeight(0);
            String name = password.getName().toUpperCase(Locale.ROOT);
            for (var keyWord : keyWords)
            {
                password.setSortingWeight(password.getSortingWeight() + searchString(name, keyWord.toUpperCase(Locale.ROOT)));
            }
        });

        PasswordBook.Passwords.sort((last1, last2) -> {
            float result = last2.getSortingWeight() - last1.getSortingWeight();
            if (result > 0)
            {
                return BIGGER;
            }
            else if (result < 0)
            {
                return SMALLER;
            }
            else if (result == 0)
            {
                return EQUAL;
            }
            return (int)result;
        });
    }

    private static float searchString(CharSequence content, CharSequence target)
    {
        float sortWeight = 0;
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(target))
        {
            return 0;
        }
        compareFirst:
        for (int i = 0; i < content.length(); )
        {
            if (content.charAt(i) == content.charAt(0))
            {
                for (int j = 0; j < target.length(); j++)
                {
                    int currentIndex = i + j;
                    if (currentIndex >= content.length() || content.charAt(currentIndex) != target.charAt(j))
                    {
                        ++i;
                        continue compareFirst;
                    }
                }
                sortWeight += (float)(content.length() - i)/ (float)content.length();
                i += target.length();
            }
            ++i;
        }
        return sortWeight;
    }

    public static void reset()
    {
        PasswordBook.Passwords.sort(Comparator.comparingInt(PasswordStruct::getInitializeNO));
    }
}
